class TutorialsController < ApplicationController

  before_filter :login_required, :only => [:new, :edit, :create, :update, :destroy]
  before_filter :set_current_menu_and_title

  def index
    @tutorials = Tutorial.paginate(:per_page => 10, :page => params[:page], :order => 'created_at desc')
    @rss_tutorials = Tutorial.find(:all, :limit => 10, :order => 'created_at desc')
  end
  
  def show
    @tutorial = Tutorial.find(params[:id])
    @title = @tutorial.title
    @keywords = @tutorial.tag_list.join(' ')
    @description = @tutorial.content[0,100]
  end

  def new
    @tutorial = Tutorial.new
  end

  def edit
    @tutorial = Tutorial.find(params[:id])
    if @tutorial.user.id != current_user.id
      redirect_to "/not_found"
    end
  end

  def create
    @tutorial = Tutorial.new(params[:tutorial])
    @tutorial.user_id = current_user.id

    if @tutorial.save
      flash[:notice] = 'Tutorial was successfully created.'
      redirect_to(@tutorial)
    else
      render :action => "new"
    end
  end

  def update
    @tutorial = Tutorial.find(params[:id])
    @tutorial.user_id = current_user.id

    if @tutorial.update_attributes(params[:tutorial])
      flash[:notice] = 'Tutorial was successfully updated.'
      redirect_to(@tutorial)
    else
      render :action => "edit"
    end
  end

  def destroy
    @tutorial = Tutorial.find(params[:id])
    @tutorial.destroy

    redirect_to(tutorials_url)
  end
  
  private
    def set_current_menu_and_title
      @current_menu = :tutorial
      @title = "教程"
    end
    
end
